#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File        :   18. 四数之和.py    
@Contact     :   lhouctcs@163.com
@License     :   MIT
@Time        :   2023/2/7 22:14
@Author      :   lhou 
@Version     :   0.1.0
@Description :
"""
from typing import List


# import lib
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        result = []
        for i in range(n):
            if i > 0 and nums[i] == nums[i - 1]: continue  # 对i去重
            for j in range(i + 1, n):
                if j > i + 1 and nums[j] == nums[j - 1]: continue  # 对j去重
                l = j + 1
                r = n - 1
                while l < r:
                    s = nums[i] + nums[j] + nums[l] + nums[r]
                    if s > target:
                        r -= 1
                    if s < target:
                        l += 1
                    if s == target:
                        result.append([nums[i], nums[j], nums[l], nums[r]])
                        while l < r and nums[l] == nums[l + 1]: l += 1
                        while l < r and nums[r] == nums[r - 1]: r -= 1
                        l += 1
                        r -= 1
        return result
